package com.cyx.proxy;

import com.sun.org.apache.bcel.internal.generic.IREM;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理：
 * 1、必须实现 InvocationHandler 接口
 * 2、通过 Proxy.newProxyInstance 创建代理类实例
 */
public class DynamicProxyRent implements InvocationHandler {
    //被代理的对象
    private Object delegate;
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        System.out.println("中介带你看房");
        result = method.invoke(this.delegate,args);
        System.out.println("中介收取费用");
        return result;
    }

    //得带代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                delegate.getClass().getInterfaces(),
                this);
    }

    public void setDelegate(Object delegate) {
        this.delegate = delegate;
    }
}


class DynamicProxy{
    public static Object getProxy(Object rent){
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("中介带你看房");
                Object result= method.invoke(rent,args);
                System.out.println("中介收取费用");
                return result;
            }
        };

        return Proxy.newProxyInstance(rent.getClass().getClassLoader(),
                rent.getClass().getInterfaces(),
                h);
    }
}